<template>
  <div class="bill-list-container">
    <div class="profile-title">我的订单</div>
    <div class="order-box" v-for="item in billList">
      <div class="order-header">
        <span class="order-date">{{item.billDate}}</span>
        <span class="order-id">拾光订单号: {{item.billId}}</span>
        <span class="del-order"  @click="deleteBill(item.billId)">
          <i class="el-icon-delete"></i>
        </span>
      </div>
      <div class="order-body">
        <div class="poster">
          <img :src="item.sysSession.sysMovie.moviePoster">
        </div>
        <div class="order-content">
          <div class="movie-name">《{{item.sysSession.sysMovie.movieNameCn}}》</div>
          <div class="cinema-name">{{item.sysSession.sysCinema.cinemaName}}</div>
          <div class="hall-ticket">
            <span>{{item.sysSession.sysHall.sysHallCategory.hallCategoryName+item.sysSession.sysHall.hallName}}</span>
            <span></span>
          </div>
          <div class="show-time">{{item.sysSession.sessionDate + ' ' + item.sysSession.sysMovieRuntime.beginTime}}</div>
        </div>
        <div class="order-price">￥{{item.sysSession.sessionPrice}}</div>
        <div class="order-status">
          {{item.billState?'已完成':'未完成'}}
        </div>
        <div class="actions">
          <div>
            <span @click="showTicket(item)" class="order-detail">查看电影票</span>
          </div>
        </div>
        <div class="return">
          <div>
            <span @click="returnTicket(item.billId)" class="return-ticket">我要退票</span>
          </div>
        </div>
        <!-- 电影票弹框 -->
        <el-dialog
          title="拾光电影"
          :visible.sync="ticketDialogVisible"
          width="30%"
          center>
          <div class="ticket-container" v-for="(seatsItem, index) in seatsList" :key="index">
            <div class="ticket-header">
              <img src="@/assets/homeLogo.jpg" class="ticket-logo">
              <span class="ticket-title">电影票</span>
            </div>
            <div class="ticket-content">
              <div class="ticket-item">
                <span class="label">影院名称</span>
                <span class="value">{{ticketInfo.cinemaName}}</span>
              </div>
              <div class="ticket-item">
                <span class="label">电影名称</span>
                <span class="value">{{ticketInfo.movieName}}</span>
              </div>
              <div class="ticket-item">
                <span class="label">影厅信息</span>
                <span class="value">{{ticketInfo.hallName}}</span>
              </div>
              <div class="ticket-item">
                <span class="label">座位号</span>
                <span class="value">{{seatsItem}}</span>
              </div>
              <div class="ticket-item">
                <span class="label">放映时间</span>
                <span class="value">{{ticketInfo.showTime}}</span>
              </div>
              <div class="ticket-item">
                <span class="label">票价</span>
                <span class="value price">￥{{ticketInfo.price}}</span>
              </div>
            </div>
            <div class="ticket-footer">
              <div class="qr-code">
                <!-- 这里可以放二维码图片 -->
                <img src="@/assets/qr-demo.jpg" alt="取票二维码">
              </div>
              <p class="tips">请凭此二维码取票入场</p>
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  name: "BillInfo",
  data(){
    return{
      queryInfo:{
        userId:''
      },
      billList:[
        {
          sysSession:{
            sysMovie:{
              moviePoster:''
            },
            sysCinema:{},
            sysHall:{
              sysHallCategory:{}
            },
            sysMovieRuntime:{}
          }
        }
      ],
      // 控制电影票弹框
      ticketDialogVisible: false,
      // 电影票信息
      ticketInfo: {
        cinemaName: '',
        movieName: '',
        hallName: '',
        seatInfo: '',
        showTime: '',
        price: 0
      },
      // 电影票信息（后端获取）
      // ticketList: [],
      // 单个订单的座位列表信息
      seatsList: []
    }
  },
  methods:{
    getUser(){
      this.queryInfo.userId = JSON.parse(window.sessionStorage.getItem('loginUser')).userId
    },
    async getBillList() {
      try {
        const response = await axios.get('sysBill', { params: this.queryInfo });
        this.billList = response.data.data || []; // 确保billList始终是数组
        console.log('billList', this.billList);

        // 处理数据前先验证结构
        this.billList = this.billList.map(item => {
          // 确保sysSession存在
          const session = item.sysSession || {};

          // 确保sysHall存在
          const hall = session.sysHall || {};

          // 确保sysHallCategory存在
          const category = hall.sysHallCategory || { hallCategoryName: '未知' };

          return {
            ...item,
            sysSession: {
              ...session,
              sysHall: {
                ...hall,
                sysHallCategory: category
              },
              sessionDate: moment(session.sessionDate).format('YYYY年MM月DD日')
            }
          };
        });

        // 按照billDate从最近到最远排序
        this.billList.sort((a, b) => {
          const dateA = moment(a.billDate);
          const dateB = moment(b.billDate);
          return dateB.diff(dateA); // 降序排列
        });

      } catch (error) {
        console.error('获取账单列表失败', error);
        // 处理错误，如显示提示信息
      }
    },
    async deleteBill(id){
      const _this = this
      const resp = await this.$confirm('此操作将永久删除订单信息,是否继续?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err=>err)
      if(resp=="cancel"){
        return _this.$message.info('已取消删除')
      }
      await axios.delete('sysBill/'+id).then(resp=>{
        if (resp.data.code !== 200){
          this.$message.success('删除失败！')
        }
      })
      this.getBillList()
      this.$message.success('删除成功！')
    },
    async returnTicket(id){
      const _this = this
      const resp = await this.$confirm('此操作将退票,是否继续?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err=>err)
      if(resp=="cancel"){
        return _this.$message.info('已取消退票')
      }
      await axios.delete('sysBill/'+id).then(resp=>{
        if (resp.data.code !== 200){
          this.$message.success('退票失败！')
        }
      })
      this.getBillList()
      this.$message.success('退票成功！')
    },
    async showTicket(item) {
      this.seatsList = JSON.parse(item.seats)
      console.log('订单信息billList.item', item, '座位列表seatsList', this.seatsList)
      this.ticketInfo = {
        cinemaName: item.sysSession.sysCinema.cinemaName,
        movieName: item.sysSession.sysMovie.movieNameCn,
        hallName: item.sysSession.sysHall.sysHallCategory.hallCategoryName + item.sysSession.sysHall.hallName,
        seatInfo: item.seats, // 这里需要从后端获取座位信息
        showTime: item.sysSession.sessionDate + ' ' + item.sysSession.sysMovieRuntime.beginTime,
        price: item.sysSession.sessionPrice
      }
      this.ticketDialogVisible = true
      // const resp = await axios.get('sysTicket/'+ item.billId)
      // console.log('电影票信息', resp.data.data)
    }
    // async showTicket(item) {
    //   const billId = item.billId;
    //   try {
    //     const res = await axios.get(`/ticket/generate/${billId}`);
    //     if (res.data.code === 200) {
    //       const tickets = res.data.data;
    //       console.log('获取电影票信息res', res, '电影票信息tickets', tickets);
          
    //       // 解析 seatInfo 字段为数组
    //         this.ticketList = tickets.map(ticket => {
    //           let seats = [];
    //           try {
    //             seats = JSON.parse(ticket.seatInfo);
    //           } catch (e) {
    //             console.error("座位信息解析失败", e);
    //           }

    //           return {
    //             cinemaName: item.sysSession.sysCinema.cinemaName,
    //             movieName: ticket.movieNameCn,
    //             hallName: ticket.hallCategoryName + ticket.hallTips,
    //             seatInfo: seats, // 解析后的座位数组
    //             showTime: ticket.sessionDate,
    //             price: ticket.ticketPrice,
    //             ticketId: ticket.ticketId
    //           };
    //         });
    //         this.ticketDialogVisible = true;
    //       } else {
    //         this.$message.error('获取电影票信息失败');
    //       }
    //   }
    //   } catch (error) {
    //     console.error('请求电影票接口出错', error);
    //     this.$message.error('网络异常，请稍后再试');
    //   }
    // }
  },
  created() {
    this.getUser()
    this.getBillList()
  }
}
</script>

<style scoped>
.bill-list-container{
  min-height: 900px;
}

.profile-title {
  padding: 26px 0;
  color: #ec443f;
  font-size: 18px;
  border-bottom: 1px solid #e1e1e1;
  margin-bottom: 30px;
}

.order-box {
  border: 1px solid #e5e5e5;
  margin: 0 40px 30px 0;
}

.order-box .order-header {
  background-color: #f7f7f7;
  font-size: 14px;
  padding: 16px 20px;
}

.order-box .order-header .order-date {
  color: #333;
  display: inline-block;
  margin-right: 30px;
}

.order-box .order-header .order-id {
  color: #999;
}

.del-order{
  float: right;
  cursor: pointer;
}

.order-box .order-body {
  padding: 20px;
  padding-right: 0;
  display: flex;
}

.order-box .order-body .poster {
  width: 66px;
  height: 91px;
  margin-right: 11px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

.poster img{
  width: 100%;
  height: 100%;
}

.order-content{
  width: 49%;
}

.movie-name{
  font-size: 16px;
  font-weight: 700;
  color: #333;
  margin: 4px 0 7px -6px;
}

.cinema-name, .hall-ticket {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.show-time {
  font-size: 12px;
  color: #f03d37;
}

.order-price, .order-status, .actions, .return{
  font-size: 14px;
  color: #333;
  width: 12%;
  line-height: 95px;
}

a {
  text-decoration: none;
  cursor: pointer;
  color: #333;
}

.order-detail, .return-ticket {
  cursor: pointer;
}

.order-detail:hover, .return-ticket:hover {
  color: #409EFF;
}

.ticket-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  position: relative;
}

.ticket-header {
  display: flex;
  justify-self: center;
  align-items: center;
  text-align: center;
  padding-bottom: 20px;
  border-bottom: 1px dashed #ddd;
  margin-bottom: 20px;
}

.ticket-logo {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.ticket-title {
  font-size: 24px;
  color: #333;
  font-weight: bold;
}

.ticket-content {
  padding: 0 20px;
}

.ticket-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 14px;
  line-height: 20px;
}

.ticket-item .label {
  color: #999;
  flex: 0 0 80px;
}

.ticket-item .value {
  color: #333;
  flex: 1;
  text-align: right;
  font-weight: 500;
}

.ticket-item .price {
  color: #f03d37;
  font-size: 16px;
  font-weight: bold;
}

.ticket-footer {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #ddd;
}

.qr-code {
  width: 100px;
  height: 100px;
  margin: 0 auto;
}

.qr-code img {
  width: 100%;
  height: 100%;
}

.tips {
  color: #999;
  font-size: 12px;
  margin-top: 10px;
}

/* 添加票根效果 */
.ticket-container:before,
.ticket-container:after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  background: #f4f4f4;
  border-radius: 50%;
}

.ticket-container:before {
  top: 50%;
  left: -10px;
  transform: translateY(-50%);
}

.ticket-container:after {
  top: 50%;
  right: -10px;
  transform: translateY(-50%);
}
</style>